//
//  YHYFindSearchViewController.m
//  LANGirl
//
//  Created by 杨泓晔 on 16/3/30.
//
//

#import "YHYFindSearchViewController.h"
#import "YHYSearchCollectionViewCell.h"
#import "YHYSHeadCollectionReusableView.h"
#import "YHYFootCollectionReusableView.h"
#import "YHYSearchAddressViewController.h"
#import "YHYViewController.h"
#import "FindViewController.h"
#import "YHYSearchTextBarCollectionCell.h"
#import "YHYSearchCollectionReusableView.h"
#import "YHYRemoveCollectionViewCell.h"
#import "YHYSearHistoryNameCollCell.h"
@interface YHYFindSearchViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchBarDelegate,UISearchResultsUpdating,UITextFieldDelegate,YHYViewControllerDeleagte>
{
    UIView *searchView;
}
@property (nonatomic,retain)UIView *myheaderView;
@property (nonatomic,retain)UICollectionView *myCollectionView;
@property (nonatomic,retain)NSMutableArray *array;
@property (nonatomic,retain)UIButton *SSbution;


@property(nonatomic,retain)UISearchBar *mySearchBar;
@property(nonatomic,retain)UISearchDisplayController *searchDC;




@property (nonatomic,strong)NSMutableArray * searchHistory;
@property (nonatomic,strong)NSArray *myArray;//搜索记录的数组
@end

@implementation YHYFindSearchViewController

-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    
    self.navigationController.navigationBarHidden = YES;
    
    [super viewWillAppear:NO];
    [self readNSUserDefaults];
}

-(void) viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden=NO;
}

-(void)readNSUserDefaults{//取出缓存的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray * myArray = [userDefaultes arrayForKey:@"myArray"];
    self.myArray = myArray;
    [self.myCollectionView reloadData];
    // NSLog(@"myArray======%@",myArray);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = LV;
    _searchHistory = [NSMutableArray array];
    [self headView];
    [self creatView];
    
}
- (void)headView{
    //导航栏search
    self.myheaderView = [[UIView alloc]init];
    self.myheaderView.backgroundColor = HEADVC;
    self.myheaderView.userInteractionEnabled = YES;
    [self.view addSubview:self.myheaderView];
    [self.myheaderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.top.mas_equalTo(@0);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 139.00*AUTO_HEIGHT/2));
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width, 139.00*AUTO_WIDTH/2));
        
    }];
    
    
    searchView = [ UIView new];
    searchView.backgroundColor = [UIColor colorWithRed:0.133 green:0.149 blue:0.173 alpha:0.700];
    [self.myheaderView addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(25 * AUTO_HEIGHT);
        make.left.mas_equalTo(15* AUTO_WIDTH);
        make.height.mas_equalTo(139 / 2 * AUTO_HEIGHT - 35 * AUTO_HEIGHT);
        make.width.mas_equalTo (SCREEN_WIDTH - 70 * AUTO_WIDTH);
        
    }];
    //裁掉边框
    searchView.layer.masksToBounds = YES;
    //设置半径
    searchView.layer.cornerRadius = 18 *AUTO_HEIGHT;
    _addressL  = [UILabel new];
    [searchView addSubview:_addressL];
    [_addressL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5 * AUTO_HEIGHT);
        make.left.mas_equalTo(10 * AUTO_WIDTH);
        make.bottom.mas_equalTo(searchView.mas_bottom).offset( - 4 * AUTO_HEIGHT);
        
        
    }];
    _addressL.text = @"中国";
    _addressL.textAlignment = NSTextAlignmentCenter;
    _addressL.font = [UIFont fontWithName:@"Arial" size:TEXTCONTENTFONT2 * AUTO_WIDTH];
    _addressL.textColor = [UIColor whiteColor];
    _addressL.userInteractionEnabled = YES;
    UIImageView *addImageV = [UIImageView new];
    [searchView addSubview:addImageV];
    [addImageV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_addressL.mas_top).offset(10 * AUTO_HEIGHT);
        make.left.mas_equalTo(_addressL.mas_right).offset(4 * AUTO_WIDTH);
        make.size.mas_equalTo(CGSizeMake(11 * AUTO_WIDTH, 7 * AUTO_HEIGHT));
        
        
    }];
    addImageV.image = [UIImage imageNamed:@"search三角"];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(addressTap:)];
    [_addressL addGestureRecognizer:tap];
    
    
    
    UIImageView *line = [UIImageView new];
    line.backgroundColor = LINE;
    line.alpha = 0.6;
    [searchView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
      
            make.top.mas_equalTo(10 * AUTO_HEIGHT);
            make.left.mas_equalTo(addImageV.mas_right).offset(7 * AUTO_WIDTH);
            make.height.mas_equalTo(16 * AUTO_HEIGHT);
        make.width.mas_equalTo(1);
    
 
        
    }];
    
    
    
    
    self.mySearchBar = [UISearchBar new];
    [searchView addSubview:self.mySearchBar];
    [self.mySearchBar mas_makeConstraints:^(MASConstraintMaker *make) {
       make.top.mas_equalTo(_addressL);
       make.left.mas_equalTo(addImageV.mas_right).offset(12 * AUTO_WIDTH);
        make.height.mas_equalTo(40 * AUTO_HEIGHT);
       make.width.mas_equalTo(210 * AUTO_WIDTH);
        
    }];
    self.mySearchBar.placeholder = @"地址";
    [self.mySearchBar setShowsCancelButton:NO];
    self.mySearchBar.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.mySearchBar setContentMode:UIViewContentModeLeft];
    
    self.mySearchBar.delegate = self;
    
    //去掉搜索框背景

    [[[self.mySearchBar.subviews objectAtIndex:0].subviews objectAtIndex:0]removeFromSuperview];
    UIView *view =   [[self.mySearchBar.subviews objectAtIndex:0].subviews objectAtIndex:0];
    [view removeFromSuperview];
    UITextField *text = [UITextField new];
    //  [self.mySearchBar addSubview:text];
    text.backgroundColor =[UIColor clearColor];
    text.returnKeyType = UIReturnKeySearch;
    [self.mySearchBar insertSubview:text atIndex:0];
    [text mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(- 8 * AUTO_HEIGHT);
        make.left.mas_equalTo(8 * AUTO_WIDTH);
        make.height.mas_equalTo(40 * AUTO_HEIGHT);
        make.right.mas_equalTo(self.mySearchBar.mas_right).offset(0 * AUTO_WIDTH);
 
        
    }];
    //设置UITextField是否拥有一键清除的功能
    text.clearsOnBeginEditing=YES;

    //设置一键清除按钮是否出现
    text.clearButtonMode=UITextFieldViewModeNever;
    text.tintColor =[UIColor whiteColor];
    text.placeholder = @"职位，姓名";
    text.alpha = 0.6;
    [text setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    text.textColor = [UIColor whiteColor];
    text.font = [UIFont fontWithName:@"Arial" size:TEXTCONTENTFONT2 * AUTO_WIDTH];
    text.clearButtonMode = UITextFieldViewModeWhileEditing;
    text.delegate = self;
    
    
    
    
    
    //右边按钮
    self.SSbution = [[UIButton alloc]init];
    // [self.SSbution setImage:[UIImage imageNamed:@"sousuo2p-01"] forState:UIControlStateNormal];
    [self.SSbution setTitle:@"取消" forState:UIControlStateNormal];
    [self.SSbution addTarget:self action:@selector(souSuo:) forControlEvents:UIControlEventTouchUpInside];
    [self.myheaderView addSubview:self.SSbution];
    [self.SSbution mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.myheaderView).offset(51.00*AUTO_WIDTH/2);     //  相对于self.view 顶部 10
        make.right.equalTo(self.myheaderView).offset(-15.00*AUTO_WIDTH/2);    //  相对于self.view 左边 10
        make.size.mas_equalTo(CGSizeMake(40.00*AUTO_WIDTH, 30.00*AUTO_WIDTH));
        
    }];
    self.SSbution.titleLabel.font= [UIFont fontWithName:@"Arial" size:TEXTNAMEFONT * AUTO_WIDTH];
    [self.SSbution setTintColor:[UIColor whiteColor]];
    
    
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [UIView animateWithDuration:3 animations:^{
        textField.placeholder = @"                职位，姓名               ";
        
    }];
    
    [textField setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
    
    
}

-(BOOL) textFieldShouldReturn:(UITextField *)textField//搜索方式
{
    if (textField.text.length > 0) {
        [self SearchText:textField.text];//缓存搜索记录
        [self readNSUserDefaults];
        [textField resignFirstResponder];
    }
    else{
        NSLog(@"请输入查找内容");
        [textField resignFirstResponder];
    }
    
    
    return YES;
}
- (void)addressTap:(UITapGestureRecognizer*)tap{
    YHYViewController *search = [YHYViewController new];
    search.deleagte = self;
    search.mydidIndexPath = self.indeP;
    search.strname = self.addSte;
    NSLog(@"%%%%%%%ld",(long)search.mydidIndexPath.row);
    NSLog(@"name%@",search.strname);
    [self.navigationController presentViewController:search animated:YES completion:^{
        
        
        
    }];
}
//协议方法
- (void)presentaddName:(NSString *)address{
    self.addressL.text = address;
}
- (void)presentaddName:(NSString *)address indexPath:(NSIndexPath *)myIndexPath{
    self.addressL.text = address;
    self.indeP = myIndexPath;
    self.addSte = address;
}
- (void)souSuo:(UIButton *)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)creatView{
    _array= [NSMutableArray arrayWithObjects:@"室内设计师",@"室内设计师",@"室内设计师",@"室内设计师",@"室内设计师",@"室内设计师",@"室内设计师", nil];
    
    //flowLayout 控制 UICollectionView布局
    UICollectionViewFlowLayout *flowLatout = [[UICollectionViewFlowLayout alloc]init];
    _myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 139/2 * AUTO_HEIGHT, self.view.frame.size.width, self.view.frame.size.height - 230 * AUTO_HEIGHT/2) collectionViewLayout:flowLatout];
    _myCollectionView.backgroundColor = LV;
    [self.view addSubview:_myCollectionView];
    _myCollectionView.delegate = self;
    _myCollectionView.dataSource = self;
    
    [_myCollectionView registerClass:[YHYSearchCollectionViewCell class] forCellWithReuseIdentifier:@"YHYSearchCollectionViewCell"];
    [_myCollectionView registerClass:[YHYSearchCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [_myCollectionView registerClass:[YHYSearchTextBarCollectionCell class] forCellWithReuseIdentifier:@"YHYSearchTextBarCollectionCell"];
    
    
    [_myCollectionView registerClass:[YHYRemoveCollectionViewCell class] forCellWithReuseIdentifier:@"YHYRemoveCollectionViewCell"];
    [_myCollectionView registerClass:[YHYSearHistoryNameCollCell class] forCellWithReuseIdentifier:@"YHYSearHistoryNameCollCell"];
    
    [_myCollectionView registerClass:[YHYSHeadCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader  withReuseIdentifier:@"CollectionReusableView"];
    [_myCollectionView registerClass:[YHYFootCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"YHYFootCollectionReusableView"];
    [_myCollectionView registerClass:[YHYSearchCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YHYSearchCollectionReusableView"];
    
    //  [_myCollectionView reloadData];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}


//增补视图
-(UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if (kind == UICollectionElementKindSectionHeader ) {
        
        
        if (indexPath.section ==  0) {
            YHYSHeadCollectionReusableView *reusableView  = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"CollectionReusableView" forIndexPath:indexPath];
            reusableView.backgroundColor = LV;
            
            reusableView.label.text = @"职业";
            return reusableView;
            
        }
        if (indexPath.section == 1) {
            
            YHYSHeadCollectionReusableView *reusableView  = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"CollectionReusableView" forIndexPath:indexPath];
            reusableView.backgroundColor = LV;
            
            reusableView.label.text = @"户行";
            
            
            return reusableView;
        }
        else{
            
            YHYSearchCollectionReusableView *search = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"YHYSearchCollectionReusableView" forIndexPath:indexPath];
            //search.label.text = @"历史搜索";
            return search;
            
        }
        
    }
    
    
    if (kind == UICollectionElementKindSectionFooter) {
        if (indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 2) {
            YHYFootCollectionReusableView *reus = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"YHYFootCollectionReusableView" forIndexPath:indexPath];
            reus.backgroundColor = [UIColor blackColor];
            reus.alpha = 0.2;
            return reus;
            
        }
        
    }
    
    return nil;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        [self.myCollectionView deselectItemAtIndexPath:indexPath animated:YES];
        if (indexPath.row == _myArray.count + 1) {
            //清除所有历史记录
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"清除历史记录" message:@"" preferredStyle: UIAlertControllerStyleAlert];
            
            //@“ UIAlertControllerStyleAlert，改成这个就是中间弹出"
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self removeAllArray];
                _myArray = nil;
                [self.myCollectionView reloadData];
            }];

            [alertController addAction:cancelAction];
            [alertController addAction:deleteAction];
            //            [alertController addAction:archiveAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
    }
}


- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 0 || section == 1) {
        
        return UIEdgeInsetsMake(0, 15 * AUTO_HEIGHT, 20 * AUTO_WIDTH, 10 * AUTO_HEIGHT);
    }
    else{
        return UIEdgeInsetsMake(15 * AUTO_WIDTH, 15 * AUTO_HEIGHT, 15 * AUTO_WIDTH, 10 * AUTO_HEIGHT);
    }
    
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    //return CGSizeMake(self.view.bounds.size.width, 70);
    if (section == 1 || section == 0) {
        
        return CGSizeMake(SCREEN_WIDTH, 50 * AUTO_HEIGHT);
        
    }
    else{
        return CGSizeMake(SCREEN_WIDTH, 0 );
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10* AUTO_HEIGHT;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0 * AUTO_WIDTH;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == 0 || section == 1) {
        return CGSizeMake(SCREEN_WIDTH, 0.5 * AUTO_HEIGHT);
    }
    else{
        return CGSizeMake(SCREEN_WIDTH, 0.5 * AUTO_HEIGHT);
    }
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0){
        CGSize de = [[_array objectAtIndex:indexPath.row ] sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(0, MAXFLOAT) lineBreakMode:UILineBreakModeCharacterWrap];
        
        return CGSizeMake(de.width + 10 * AUTO_WIDTH, 30 * AUTO_HEIGHT);
        
        
    }if(indexPath.section == 1) {
        
        CGSize de = [[_array objectAtIndex:indexPath.row ] sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(200, MAXFLOAT) lineBreakMode:UILineBreakModeCharacterWrap];
        
        
        return CGSizeMake(de.width + 10 * AUTO_WIDTH, 30 * AUTO_HEIGHT);
        
        
        
    }
    if (indexPath.section == 2) {
        return CGSizeMake(SCREEN_WIDTH, 30 * AUTO_HEIGHT);
        
    }
    return CGSizeMake(0, 0);
    
    
    
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0){
        return _array.count;
    }
    if(section == 1) {
        return _array.count;
    }
    if (section == 2){
        if (_myArray.count > 0) {
            return _myArray.count + 1 + 1;
        }
        else{
            return 1;
        }
        
    }
    return 0;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        static NSString *sta = @"YHYSearchCollectionViewCell";
        YHYSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:sta forIndexPath:indexPath];
        cell.textL.text = [_array objectAtIndex:indexPath.row];
        CGSize de = [[_array objectAtIndex:indexPath.row ] sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(0, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
        
        
        cell.sizeWH =  de;
        
        return cell;
        
    }
    if(indexPath.section == 1) {
        
        static NSString *sta = @"cell";
        YHYSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:sta forIndexPath:indexPath];
        cell.textL.text = [_array objectAtIndex:indexPath.row];
        CGSize de = [[_array objectAtIndex:indexPath.row ] sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(0, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
        cell.sizeWH =  de;
        
        
        return cell;
        
    }
    
    if (indexPath.section == 2) {
        if (indexPath.row == 0) {
            static NSString *sta = @"YHYSearHistoryNameCollCell";
            YHYSearHistoryNameCollCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:sta forIndexPath:indexPath];
            cell.textL.text = @"历史搜索";
            cell.textL.alpha = 0.6;
            cell.textL.font = [UIFont fontWithName:@"Arial" size:TEXTCONTENTFONT * AUTO_WIDTH];
            cell.textL.textColor = [UIColor blackColor];
            return cell;
        }
        else if (indexPath.row == _myArray.count + 1){
            static NSString *sta = @"YHYRemoveCollectionViewCell";
            YHYRemoveCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:sta forIndexPath:indexPath];
            cell.textL.text = @"清楚搜索记录";
            
            return cell;
            
        }
        else{
            static NSString *sta = @"YHYSearchTextBarCollectionCell";
            YHYSearchTextBarCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:sta forIndexPath:indexPath];
            NSArray* reversedArray = [[_myArray reverseObjectEnumerator] allObjects];
            cell.textL.text = reversedArray[indexPath.row-1];
            
                       return cell;
            
        }
    }
    else{
        static NSString *sta = @"YHYSearchTextBarCollectionCell";
        YHYSearchTextBarCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:sta forIndexPath:indexPath];
        return cell;
        
    }
    
}

//缓存搜索数组
- (void)SearchText:(NSString *)seaTxt{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray *myArray = [userDefaultes arrayForKey:@"myArray"];
    if (myArray.count > 0) {//先取出数组，判断是否有值，有值继续添加，无值创建数组
        
    }
    else{
        myArray = [NSArray array];
    }
    NSMutableArray *searTXT = [myArray mutableCopy];
    [searTXT addObject:seaTxt];
    if (searTXT.count > 5) {
        [searTXT removeObjectAtIndex:0];//???
    }
    //将上述数据全部存储到NSUserDefaults中
    [userDefaultes setObject:searTXT forKey:@"myArray"];
    [userDefaultes synchronize];
    
}

- (void)removeAllArray{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"myArray"];
    [userDefaults synchronize];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
